package GUI;
import controller.Controller;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class UserGUI{
    private static Controller controller = new Controller();
    private String searchString;
    private ArrayList<String> findGoods = new ArrayList<>();
    private ArrayList<String> cartArrayList = new ArrayList<>();
    private int flag = 0;
    private Vector<Vector<java.io.Serializable>> cartsData = createCarData();//初始数据
    private Vector<String> carColumnNames = createCarColumnNames();
    private JTable carTable =null;
    private  DefaultTableModel cartTableModel;
    private DefaultTableModel orderTableModel;
    private Vector<String> myOrderColumnNames = createMyOrderColumnNames();
    private JTable  myOrderTable =null;
    private Vector<Vector<Serializable>> myOrderData = createMyOrderData();
    public UserGUI()
    {
        gui();
    }
    private void  gui() {
        JFrame frame = new JFrame("皇家购物系统");
        JTabbedPane tabbedPane= new JTabbedPane();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        JPanel panel3 = new JPanel(new BorderLayout());

        //主页panel1中的布局
        JPanel panel11 = new JPanel(new FlowLayout());
        JLabel label = new JLabel("请输入商品名称：");
        label.setFont(new Font("宋体",Font.BOLD,20));
        JTextField textField = new JTextField(10);
        textField.setFont(new Font("宋体",Font.PLAIN,20));
        JButton button = new JButton("搜索");
        button.setFont(new Font("宋体",Font.PLAIN,20));
        button.setSize(200,10);

        panel11.add(label);
        panel11.add(textField);
        panel11.add(button);
        panel1.add(panel11,BorderLayout.NORTH);
        //表格设计
        Vector<String> columnNames = createColumnNames();
        Vector searchData = createSearchData();
        DefaultTableModel defaultModel1 = new DefaultTableModel(searchData,columnNames){
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };//表格不可编辑
        JTable table1 = new JTable(defaultModel1);
        table1.setFont(new Font("宋体",Font.PLAIN,20));
        table1.getTableHeader().setFont(new Font("宋体",Font.PLAIN,20));
        table1.setRowHeight(25);
        table1.getTableHeader().setReorderingAllowed(false);
        JScrollPane scrollPane = new JScrollPane(
                table1,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
        );
        panel1.add(scrollPane,BorderLayout.CENTER);
        //使表格内容居中
        DefaultTableCellRenderer decr = new DefaultTableCellRenderer();
        decr.setHorizontalAlignment(JLabel.CENTER);
        table1.setDefaultRenderer(Object.class,decr);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchString = textField.getText();
                textField.setText(null);
                if(flag==1) {
                    defaultModel1.setRowCount(0);
                    findGoods.clear();
                }else{
                    flag = 1;
                }

                findGoods = controller.findUserGUI();
                if (findGoods.size() != 0 && findGoods.get(0).equals("无法查找此商品！")) {
                    JOptionPane.showMessageDialog(null, "无法查找此商品！");
                } else {
                    for (int i = 0; i < findGoods.size(); i++) {
                        String[] temp = findGoods.get(i).split(" ");
                        String[] data = {temp[0], temp[1], temp[2], temp[3]};
                        defaultModel1.addRow(data);
                        int selectedRow = table1.getSelectedRow() + 1;
                    }
                }

            }

        });


        JButton button1 = new JButton("添加到购物车");
        button1.setFont(new Font("宋体",Font.PLAIN,20));
        button1.setSize(200,10);
        panel1.add(button1,BorderLayout.SOUTH);
        button1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                //String name = textField.getText();
                int selectedRow =table1.getSelectedRow();//获取当前选中行
                cartArrayList.add(findGoods.get(selectedRow));
                controller.addCartArrayList(cartArrayList);
                JOptionPane.showMessageDialog(null, "添加成功！");
                cartsData = createCarData();//初始数据
                cartArrayList.clear();
            }
        });





        //购物车页面布局

        cartTableModel = new DefaultTableModel(cartsData,carColumnNames){
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };//表格不可编辑
        carTable = new JTable(cartTableModel);
        carTable.getTableHeader().setReorderingAllowed(false);
        JScrollPane scrollPane2 = new JScrollPane(
                carTable,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
        );
        carTable.setFont(new Font("宋体",Font.PLAIN,20));
        carTable.getTableHeader().setFont(new Font("宋体",Font.PLAIN,20));
        carTable.setRowHeight(25);
        //使表格内容居中
        DefaultTableCellRenderer dear1 = new DefaultTableCellRenderer();
        dear1.setHorizontalAlignment(JLabel.CENTER);
        carTable.setDefaultRenderer(Object.class,dear1);

        panel2.add(scrollPane2,BorderLayout.CENTER);
        JPanel panel21 = new JPanel(new FlowLayout());
        JButton deleteButton = new JButton("删除商品");
        JButton button3 = new JButton("结算");
        deleteButton.setFont(new Font("宋体",Font.PLAIN,20));
        deleteButton.setSize(200,10);
        button3.setFont(new Font("宋体",Font.PLAIN,20));
        button3.setSize(200,10);
        //*********
        JButton button4 = new JButton("刷新");
        button4.setFont(new Font("宋体",Font.PLAIN,20));
        button4.setSize(200,10);
        panel21.add(button4);
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cartTableModel.getDataVector().clear();
                carTable.validate();
                carTable.updateUI();

                cartsData = createCarData();
                cartTableModel = new DefaultTableModel(cartsData,carColumnNames){
                    public boolean isCellEditable(int row, int column) {
                        return false;
                    }
                };//表格不可编辑
              //  defaultModel2.fireTableStructureChanged();
                carTable.setModel(cartTableModel);
                DefaultTableCellRenderer dear1 = new DefaultTableCellRenderer();
                dear1.setHorizontalAlignment(JLabel.CENTER);
                carTable.setDefaultRenderer(Object.class,dear1);
            }
        });
        //********
        panel21.add(deleteButton);
        panel21.add(button3);
        panel2.add(panel21,BorderLayout.SOUTH);
        //删除按钮触发器
        deleteButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                int selectedRow =carTable.getSelectedRow();
                if(selectedRow!=-1) {
                    cartArrayList = controller.getCartArrayList();
                    cartTableModel.removeRow(selectedRow);
                    System.out.println(selectedRow);
                    cartArrayList.remove(selectedRow);
                    controller.deleteCartArrayList(cartArrayList);
                    cartArrayList.clear();
                }
            }
        });
        //结算按钮触发器
        button3.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                new OrderGUI();
            }
        });


        //我的页面布局
        JPanel panel31 = new JPanel(new FlowLayout());
        JLabel label1 = new JLabel("历史订单如下:                                     ");
        label1.setFont(new Font("宋体",Font.PLAIN,20));
        JButton button2 = new JButton("刷新");
        button2.setFont(new Font("宋体",Font.PLAIN,20));
        button2.setSize(200,10);
        panel31.add(label1);
        panel31.add(button2);
        panel3.add(panel31,BorderLayout.NORTH);



        myOrderData =  createMyOrderData();
        orderTableModel = new DefaultTableModel(myOrderData,myOrderColumnNames){
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };//表格不可编辑
        myOrderTable = new JTable(orderTableModel);
        JScrollPane scrollPane3 = new JScrollPane(
                myOrderTable,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
        );
        //使表格内容居中
        DefaultTableCellRenderer dtcr2 = new DefaultTableCellRenderer();
        decr.setHorizontalAlignment(JLabel.CENTER);
        myOrderTable.setDefaultRenderer(Object.class,dtcr2);
        myOrderTable.setFont(new Font("宋体",Font.PLAIN,20));
        myOrderTable.getTableHeader().setFont(new Font("宋体",Font.PLAIN,20));
        myOrderTable.setRowHeight(25);
        myOrderTable.getTableHeader().setReorderingAllowed(false);
        //*******
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                orderTableModel.getDataVector().clear();
                myOrderTable.validate();
                myOrderTable.updateUI();

                myOrderData = createMyOrderData();
                orderTableModel = new DefaultTableModel(myOrderData,myOrderColumnNames){
                    public boolean isCellEditable(int row, int column) {
                        return false;
                    }
                };//表格不可编辑

                  //defaultModel2.fireTableStructureChanged();
                myOrderTable.setModel(orderTableModel);
                DefaultTableCellRenderer dear1 = new DefaultTableCellRenderer();
                dear1.setHorizontalAlignment(JLabel.CENTER);
                myOrderTable.setDefaultRenderer(Object.class,dear1);
            }
        });

        panel3.add(scrollPane3,BorderLayout.CENTER);


        tabbedPane.addTab("主页", null,panel1);
        tabbedPane.addTab("购物车", null,panel2);
        tabbedPane.addTab("我的", null,panel3);
        tabbedPane.setFont(new Font("宋体",Font.PLAIN,20));


        frame.add(tabbedPane);
        frame.pack();
        frame.setVisible(true);
        frame.setBounds((Toolkit.getDefaultToolkit().getScreenSize().width)/2-600, (Toolkit.getDefaultToolkit().getScreenSize().height/2)-400, 1200,750);
    }
    private Vector<String> createColumnNames()//搜索界面表格的表头
    {
        Vector<String> columnNames = new Vector<>();
        columnNames.add("商品编号");
        columnNames.add("商品名称");
        columnNames.add("单价(元）");
        columnNames.add("库存");
        return columnNames;
    }
    private Vector createSearchData()//搜索界面的表格数据
    {
        /*
        Vector<Object> data = new Vector<>();
        findGoods.get(0) == "无法查找此商品！"；
        */

        return new Vector();
    }
    private Vector<String> createCarColumnNames()//购物车表格的表头
    {
        Vector<String> columnNames = new Vector<>();
        columnNames.add("商品编号");
        columnNames.add("商品名称");
        columnNames.add("单价(元）");
        columnNames.add("数量");
        columnNames.add("总价");
        return columnNames;
    }

    private Vector<Vector<Serializable>> createCarData()//购物车表格的数据
    {
        //rowData1.add(new Boolean(false)); //每次添加的一行信息都得加这句
        ArrayList<String> myCartArrayList = controller.getCartArrayList();
        Vector<Vector<Serializable>> cartData = new Vector<>();
        cartData.clear();
        if(myCartArrayList.get(0).contains("null")){
            myCartArrayList.remove(0);
        }
        for(int j = 0; j< myCartArrayList.size(); j++)
        {
            Vector<Serializable> cartsData = new Vector<>();
            String[] temp = myCartArrayList.get(j).split(" ");
            String[] data = {temp[0], temp[1], temp[2], temp[3]};
            cartsData.add(temp[0]);//编号
            cartsData.add(temp[1]);//名称
            cartsData.add(temp[2]);//价格
            double price = Double.parseDouble(temp[2]);
            int num = Integer.parseInt(temp[3]);
            double totalPrice = price*num;
            cartsData.add(num);
            cartsData.add(totalPrice);//总价
            cartData.add(cartsData);
        }
        return cartData;
    }
    private Vector<String> createMyOrderColumnNames()//我的订单表格表头
    {
        Vector<String> columnNames = new Vector<>();
        columnNames.add("订单编号");
        columnNames.add("订单创建时间");
        columnNames.add("商品名称");
        columnNames.add("单价(元）");
        columnNames.add("数量");
        return columnNames;
    }
    private Vector<Vector<Serializable>> createMyOrderData()
    {
        Vector<Vector<Serializable>> orderData = new Vector<>();
        ArrayList<String> orderArrayList = controller.getOderArrayList();

        //orderData.clear();
        //if(orderArrayList.get(0).contains("null")){
         //   orderArrayList.remove(0);
        //}


        for(int j = 0; j< orderArrayList.size(); j++)
        {
            Vector<Serializable> ordersData = new Vector<>();
            String[] temp = orderArrayList.get(j).split(" ");
            String[] data = {temp[0], temp[1], temp[2], temp[3],temp[4]};
            ordersData.add(temp[0]);//订单编号
            ordersData.add(temp[1]);//订单创建时间
            ordersData.add(temp[2]);//商品名称
            ordersData.add(temp[3]);//单价
            ordersData.add(temp[4]);//数量
            orderData.add(ordersData);
        }

        return orderData;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setFindGoods(ArrayList<String> findGoods) {
        this.findGoods = findGoods;
    }


}
